import request from '@/utils/request.js'
import store from '@/store/index.js'
//用户频道列表
export async function channels() {
    //如果用户没有登入
  if (!store.state.user.token) {
      //获取本地存储的频道数据
    const _local = JSON.parse(localStorage.getItem('userChannels')) || []
    if (_local.length === 0) {
        //调用接口获取本地频道数据
      const res = await request({
        url: '/v1_0/user/channels'
      })
      //存储频道到本地
      localStorage.setItem('userChannels', JSON.stringify(res.data.channels))
      //将数据return出去
      return res.data.channels
    } else {
        //本地有数据直接return
      return _local
    }

  } else {
      //用户登入直接调用接口
    const res = await request({
      url: '/v1_0/user/channels'
    })
    return res.data.channels
  }
}
//文章新闻推荐
export function articlesGet(params) {
  return request({
    url: '/v1_0/articles',
    params
  })
}
//获取所有用户频道
export function channelsAll() {
  return request({
    url: '/v1_0/channels',
  })
}
//全量修改
export async function userChannelsPut(channels){
    if(store.state.user.token){
        return request({
            url:'/v1_0/user/channels',
            method:'put',
            data:{
                channels
            }
        })
    }else {
        localStorage.setItem('userChannels',JSON.stringify(channels))
    }
}
